<?php
class CentImsMailer implements IMailer {
	/**
	 * 邮件发送器
	 * @var PHPMailer
	 */
	private $phpmailer;
	public function __construct() {
		$this->phpmailer = new PHPMailer ( true );
		$this->config ();
	}
	/*
	 * (non-PHPdoc) @see IMailer::send()
	 */
	public function send($to, $subject, $message, $attachments = array()) {
		try {
			$this->phpmailer->reset ();
			$this->phpmailer->Subject = $subject;
			if ($this->phpmailer->ContentType == 'text/html') {
				$this->phpmailer->MsgHTML ( $message, WWW_ROOT );
			} else {
				$this->phpmailer->Body = $message;
				$this->phpmailer->WordWrap = 66;
			}
			if (! is_array ( $to )) {
				$_to = explode ( '@', $to );
				$to = array ($to, $_to [0] );
			}
			$this->phpmailer->AddAddress ( $to [0], $to [1] );
			if (! empty ( $attachments )) {
				$attachments = is_array ( $attachments ) ? $attachments : array ($attachments );
				foreach ( $attachments as $i => $att ) {
					$this->phpmailer->AddAttachment ( $att, 'attach-' . $i );
				}
			}
			return $this->phpmailer->Send ();
		} catch ( phpmailerException $e ) {
			elog ( "邮件发送失败:" . $e->getMessage () );
			return false;
		} catch ( Exception $e ) {
			elog ( "邮件发送失败:" . $e->getMessage () );
			return false;
		}
	}
	
	/*
	 * (non-PHPdoc) @see IMailer::setMessageType()
	 */
	public function setMessageType($type) {
		if ($type == 'html') {
			$this->phpmailer->IsHTML ( true );
		} else {
			$this->phpmailer->IsHTML ( false );
		}
	}
	private function config() {
		$type = CoreOptionModel::getOption ( 'smtp_type', 'smtp' );
		switch ($type) {
			case 'mail' :
				$this->phpmailer->IsMail ();
				break;
			case 'sendmail' :
				$this->phpmailer->IsSendmail ();
				break;
			case 'qmail' :
				$this->phpmailer->IsQmail ();
				break;
			case 'smtp' :
			default :
				$this->phpmailer->IsSMTP ();
				$this->phpmailer->SMTPAuth = true;
				$this->phpmailer->Username = CoreOptionModel::getOption ( 'smtp_user', 'root@localhost' );
				$this->phpmailer->Password = CoreOptionModel::getOption ( 'smtp_passwd', 'root' );
				$this->phpmailer->Host = CoreOptionModel::getOption ( 'smtp_host', 'localhost' );
				$this->phpmailer->Port = CoreOptionModel::getOption ( 'smtp_port', 25 );
				$this->phpmailer->SMTPSecure = CoreOptionModel::getOption ( 'smtp_secure', '' );
				break;
		}
		$this->phpmailer->CharSet = 'UTF-8';
		$this->phpmailer->Encoding = 'base64';
		$this->phpmailer->FromName = CoreOptionModel::getOption ( 'smtp_from', 'CentIMS' );
		$this->phpmailer->From = CoreOptionModel::getOption ( 'smtp_reply', 'no-reply@centims.com' );
		$this->phpmailer->AddReplyTo ( $this->phpmailer->From, $this->phpmailer->FromName );
		$this->phpmailer->IsHTML ( true );
	}
}